package mud.mongo;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;

public class MongoHelper {
	MongoClient client;
	MongoDatabase db;
	MongoCollection<Document> collection;

	/*
	 * // or MongoClient client = new MongoClient( "localhost" );
	 * // or MongoClient client = new MongoClient( "localhost" , 27017);
	 * // or use a connection string MongoClientURI connectionString = new
	 * MongoClientURI(
	 * "mongodb://localhost:27017,localhost:27018,localhost:27019"); MongoClient
	 * client = new MongoClient(connectionString);
	 */

	public MongoHelper(String dbName) {
		client = new MongoClient();
		db = client.getDatabase(dbName);
	}

	public void setCollection(String collName) {
		collection = db.getCollection(collName);
	}

	public void insertDoc(Document doc) {
		collection.insertOne(doc);
	}

	public long getDocCount() {
		return collection.count();
	}

	public String findFirstDoc() {
		Document doc = collection.find().first();
		return doc.toJson();
	}

	public void printAllDoc() {
		MongoCursor<Document> cursor = collection.find().iterator();
		try {
			while (cursor.hasNext()) {
				System.out.println(cursor.next().toJson());
			}
		} finally {
			cursor.close();
		}
	}
}
